package com.concurrency.juc.synctools.keywords;

import java.util.concurrent.TimeUnit;

public class VolatileDemo1 {
    public static void main(String[] args) {
        ThreadDemo demo = new ThreadDemo();
        new Thread(demo).start();
//        while (!demo.isFlag()) {
//            System.out.println("等待flag变量修改中");
//        }
        //使用synchronize关键字
        while (true){
            synchronized (demo){
                if(demo.isFlag()){
                    System.out.println("命中变量修改");
                    break;
                }
            }
        }
    }

    static class ThreadDemo implements Runnable {
        //如果这里不适用volatile 程序将无法退出
        public volatile boolean flag = false;

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
            System.out.println("ThreadDemo线程修改后的flag:" + isFlag());
        }
    }

}
